<template>
  <div class="mod-prod">
    <!-- 区块链信息卡片 -->
    <el-card class="block-info-card">
      <template #header>
        <div class="card-header">
          <i
            class="el-icon-connection"
            style="margin-right: 10px;"
          />
          <h1 style="margin: 0;color: #2c3e50;">
            区块链信息看板
          </h1>
        </div>
      </template>
      <div
        v-if="blockInfo"
        class="info-container"
      >
        <el-row :gutter="20">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
          >
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-copy-document" />
                最后一个区块哈希
              </div>
              <div class="info-value hash-value">
                {{ blockInfo.blockHash }}
              </div>
            </div>
          </el-col>
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
          >
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-data-line" />
                区块编号
              </div>
              <div class="info-value number-value">
                #{{ blockInfo.blockNumber }}
              </div>
            </div>
          </el-col>
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
          >
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-coin" />
                链上资产数量
              </div>
              <div class="info-value asset-value">
                {{ assetNumber }} 项
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div
        v-else-if="loading"
        class="loading-container"
      >
        <el-progress
          type="circle"
          :percentage="100"
          status="warning"
          :indeterminate="true"
          :width="80"
          :show-text="false"
        />
        <p class="loading-text">
          区块链信息加载中...
        </p>
      </div>
      <div v-else>
        <el-alert
          type="error"
          title="无法加载区块链信息"
          :closable="false"
        />
      </div>
    </el-card>

    <!-- 资产列表表格 -->
    <!-- 资产列表表格 -->
    <avue-crud
      ref="crudRef"
      :page="page"
      :data="dataList"
      :option="tableOption"
      @search-change="onSearch"
      @on-load="getDataList"
    >
      <!--  支付类型图标插槽添加在这里 -->
      <template #payType="{ row }">
        <div class="full-cell-container">
          <!-- 微信支付 -->
          <div
            v-if="row.payType === 1"
            class="image-container"
          >
            <img
              :src="wxpaylogo"
              class="full-size-image"
            >
          </div>

          <!-- 支付宝 -->
          <div
            v-else-if="row.payType === 2"
            class="image-container"
          >
            <img
              :src="zhifubaopaylogo"
              class="full-size-image"
            >
          </div>

          <!-- 新增银联支付 -->
          <div
            v-else-if="row.payType === 0"
            class="image-container"
          >
            <img
              :src="yinlianpaylogo"
              class="full-size-image"
            >
          </div>

          <!-- 其他类型（图标） -->
          <div
            v-else
            class="icon-container"
          >
            <i
              :class="PAY_TYPE_MAP[row.payType]?.icon || 'el-icon-question'"
              class="full-size-icon"
            />
          </div>
        </div>
      </template>
    </avue-crud>
  </div>
</template>

<script setup>
import { ref, onMounted, h } from 'vue'
import { ElMessage, ElProgress, ElRow, ElCol, ElTag, ElAlert } from 'element-plus'
import http from '@/utils/http'
import { tableOption } from '@/crud/home/orderinfo.js'
// 新增日期库引入
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import wxpaylogo from '@/assets/img/wxpaylogo.png'
import zhifubaopaylogo from '@/assets/img/zhifubaopay.png'
import yinlianpaylogo from '@/assets/img/yinlianpay.png'
dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.tz.setDefault('Asia/Shanghai') // 根据实际时区设置

const PAY_TYPE_MAP = {
  0: { text: '手动代付', icon: yinlianpaylogo },
  1: { text: '微信支付', icon: wxpaylogo },
  2: { text: '支付宝', icon: zhifubaopaylogo }
}
// 区块链信息相关
const blockInfo = ref(null)
const loading = ref(false)
const assetNumber = ref(0)

// 表格相关
const dataList = ref([])
const page = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

onMounted(() => {
  fetchBlockInfo()
  fetchAssetNumber()
  getDataList()
})

// 修复2：优化数据获取方法
const fetchBlockInfo = async () => {
  loading.value = true
  try {
    const response = await http({
      url: http.adornUrl('/blockInfo/lastBlockInfo'),
      method: 'get',
      timeout: 10000
    })
    console.log('完整响应结构:', response)
    blockInfo.value = response.data || response
    console.log('data', blockInfo.value)
  } catch (error) {
    const errorMsg = error.response ? `请求失败：[${error.response.status}] ${error.response.data?.message || '未知错误'}` : error.message.includes('timeout') ? '请求超时，请检查网络连接' : '网络连接异常'
    ElMessage.error({
      message: `获取区块链信息失败: ${errorMsg}`,
      duration: 3000
    })
    console.error('完整错误信息:', {
      message: error.message,
      config: error.config,
      response: error.response
    })
  } finally {
    loading.value = false
    // active.value = false
  }
}

const fetchAssetNumber = async () => {
  try {
    const response = await http({
      url: http.adornUrl('/blockInfo/getAssetNumber'),
      method: 'get',
      timeout: 10000
    })
    console.log('获取链上资产数量响应:', response.data)
    if (response.data !== null) {
      assetNumber.value = response.data
    } else {
      ElMessage.error('无法获取链上资产数量,可能资产为空')
      assetNumber.value = 0
    }
  } catch (error) {
    const errorMsg = error.response ? `请求失败：[${error.response.status}] ${error.response.data?.message || '未知错误'}` : error.message.includes('timeout') ? '请求超时，请检查网络连接' : '网络连接异常'
    ElMessage.error({
      message: `获取链上资产数量失败: ${errorMsg}`,
      duration: 3000
    })
    console.error('获取链上资产数量错误信息:', {
      message: error.message,
      config: error.config,
      response: error.response
    })
  }
}

/**
 * 获取资产列表数据
 */
// 修改 getDataList 方法
const getDataList = (pageParam, params, done) => {
  http({
    url: http.adornUrl('/blockInfo/GetAllAssetsWithPage'),
    method: 'get',
    params: http.adornParams({
      current: page.value.currentPage,
      size: page.value.pageSize,
      ...params
    })
  }).then(({ data }) => {
    // 修改这里开始
    dataList.value = data?.records ? data.records.map(item => ({
      ...item,
      createTime: item.createTime ? dayjs.tz(item.createTime).valueOf() : null,
      payTime: item.payTime ? dayjs.tz(item.payTime).valueOf() : null
    })) : [] // 关键点：无数据时设为空数组

    page.value.total = data?.total || 0 // 确保total重置为0
    if (done) done()
  })
}
/**
 * 条件查询
 */
const onSearch = (params, done) => {
  getDataList(page.value, params, done)
}
</script>

<style lang="scss" scoped>

.block-info-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  .card-header {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #eee;
  }

  .info-container {
    padding: 16px 0;

    .info-item {
      margin: 12px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .info-label {
        color: #6c757d;
        font-size: 13px;
        margin-bottom: 8px;

        i {
          margin-right: 6px;
        }
      }

      .info-value {
        font-size: 20px;
        font-weight: 600;
        color: #2c3e50;
        word-break: break-all;

        &.hash-value { color: #4a90e2; }
        &.number-value { color: #34bfa3; }
        &.asset-value { color: #f4516c; }
      }
    }
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 0;

    :deep(.el-progress-circle) {
      path:first-child { stroke: #f8f9fa; }
      path:last-child {
        stroke: #4a90e2;
        animation: loading-dash 1.5s ease-in-out infinite;
      }
    }

    .loading-text {
      margin-top: 16px;
      color: #6c757d;
      font-size: 14px;
    }
  }
}

/* 表格样式 */
:deep(.avue-crud) {
  .el-table {
    border-radius: 8px;
    overflow: hidden;

    th {
      font-weight: 600;
      background: #f8f9fa !important;
    }

    tr:hover td {
      background-color: #f8f9fa !important;
    }
  }

  .pay-type {
    display: flex;
    align-items: center;
    gap: 8px;

    .pay-logo {
      width: 24px;
      height: 24px;
      border-radius: 4px;
    }
  }

  .el-pagination {
    padding: 16px;
    justify-content: flex-end;
  }
}

@keyframes loading-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -40px;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -120px;
  }
}
// 在 <style> 中添加以下样式
:deep(.avue-crud) {
  // 支付类型列专用样式
  .el-table__body td.avue-crud__payType {
    vertical-align: middle; // 垂直居中
    .cell {
      padding: 0 !important;
    }
  }

  .full-cell-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .image-container, .icon-container {
      width: 100%;
      height: 100%;
      min-height: 40px; // 根据行高调整
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .full-size-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      padding: 4px; // 适当留白
    }

    .full-size-icon {
      font-size: 150%; // 根据列宽动态调整
      color: #409EFF;
      transform: scale(1.5); // 放大图标
    }
  }
}
</style>
